import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import Header from '../common/Header'
import { connect } from 'react-redux';
import { set_default_address_action } from '../../store/store';
import { Toast } from 'antd-mobile'
 class AddressList extends Component {
    constructor() {
        super();
        this.state = {
            currentIndex:0,//保存当前点击 地址的索引
        }
    }
    render() {
        return (
            <div className="addresslist-page">
                {/* Header组件 */}
                <Header title="我的地址列表" back={<span onClick={() => { this.props.history.go(-1); }}>&lt;</span>}></Header>
                {/*  */}
                <div className="addresslist">
                    {
                        this.props.addressList.length > 0 ?
                        this.props.addressList.map((item,index) => {
                            return (
                                <div className={`address  ${this.props.defaultAddress.id === item.id ? 'active' : ''}`} key={item.id} onClick={() => {
                                    this.setState({ currentIndex: index });
                                    this.props.set_default_address(item);
                                    Toast.success("设置默认地址成功!", 1, null, false);
                                }}>
                                    <div className="text">
                                        <div className="address-info">{item.address}</div>
                                        <div>{item.name} {item.phone}</div>
                                    </div>
                                    <Link onClick={(e)=>{ e.stopPropagation() }} className="btns" to={{ pathname:'/edit',state: item }}>
                                        编辑
                                    </Link>
                                    <div className="default">默认地址</div>
                                </div>
                            )
                        }) :
                            <div className="empty">还没有添加任何地址!</div>
                    }
                </div>
                
                {/* 新增地址 */}
                <Link className="btn-box" to="/add">
                    <div className="btn">新增地址</div>
                </Link>
            </div>
        )
    }
}

export default connect(
    (state) => {//注入数据
        return {
            addressList: state.addressList,
            defaultAddress: state.defaultAddress
        }
    },
    (dispatch) => {//注入方法
        return {
            set_default_address: (item) => {
                dispatch(set_default_address_action(item));
            }
        }
    }
)( AddressList )
